import React from 'react';
import { observer } from 'mobx-react';
import { Modal, Form, Input, InputNumber, message } from 'antd';
import http from 'libs/http';
import store from './store';

@observer
class CategoryForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    }
  }

  handleSubmit = () => {
    this.setState({ loading: true });
    const formData = this.props.form.getFieldsValue();
    formData['id'] = store.record.id;

    http.post('/api/course/category/', formData)
      .then(() => {
        message.success('操作成功');
        store.formVisible = false;
        store.fetchRecords()
      }, () => this.setState({ loading: false }))
  };

  render() {
    const info = store.record;
    const { getFieldDecorator } = this.props.form;
    const itemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    };

    return (
      <Modal
        visible
        maskClosable={false}
        title={store.record.id ? '编辑类别' : '新建类别'}
        onCancel={() => store.formVisible = false}
        confirmLoading={this.state.loading}
        onOk={this.handleSubmit}>
        <Form>
          <Form.Item {...itemLayout} required label="学校名称">
            {getFieldDecorator('school', {
              initialValue: info['school'],
              rules: [{ required: true, message: '请输入学校名称' }]
            })(
              <Input placeholder="请输入学校名称"/>
            )}
          </Form.Item>
          <Form.Item {...itemLayout} required label="课程大类">
            {getFieldDecorator('name', {
              initialValue: info['name'],
              rules: [{ required: true, message: '请输入大类别名称' }]
            })(
              <Input placeholder="请输入大类别名称"/>
            )}
          </Form.Item>
          <Form.Item {...itemLayout} label="排序">
            {getFieldDecorator('sort_id', {
              initialValue: info['sort_id'] || 0
            })(
              <InputNumber min={0} style={{width: '100%'}}/>
            )}
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(CategoryForm) 